import React, { PureComponent, Fragment } from 'react';
import {
  Row,
  Card,
  Col,
  Form,
  Button,
  Input,
  DatePicker,
  Table,
  Select,
  Icon,
  Divider,
  Popconfirm,
  Modal,
  message,
  Alert,
} from 'antd';
import moment from 'moment';
import { getAuthority } from '@/utils/authority';
import RenderAuthorized from '@/components/Authorized';

const Authorized = RenderAuthorized(getAuthority());
import { connect } from 'dva';
import router from 'umi/router';
import RepairAddForm from './components/Repair/RepairAddForm';
// import  RepairEditForm  from './components/RepairEditForm';
import RepairEditForm2 from './components/Repair/RepairEditForm2';
import Ellipsis from '@/components/Ellipsis';
// 样式
import styles from './Repair.less';
const FormItem = Form.Item;
const Option = Select.Option;

@Form.create()
@connect(({ repair, config, loading,global }) => ({
  currentUrl:global.currentUrl,
  elementAuth:global.elementAuth,
  wxglList: repair.wxglList,
  MaintainNodeList: repair.MaintainNodeList,
  loading: loading.effects['repair/fetchEquipmentList'],
}))
class Repair extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      editObj: {},
    };
    this.user_id = sessionStorage.getItem('user_id');
    this.dispatch = this.props.dispatch;
  }
  returnColumn = () => {
    return [
      {
        title: '序号',
        width: 60,
        dataIndex: 'Id',
        render: (text, record, index) => `${index + 1}`,
        width: 50,

      },
      {
        title: '任务号',
        dataIndex: 'SortCode',
        key: 'SortCode',


      },
      {
        title: '设施名称',
        dataIndex: 'EquipmentName',
        key: 'EquipmentName',

        render: text => (
          <Ellipsis length={6} tooltip>
            {text}
          </Ellipsis>
        ),
      },

      {
        title: '目前流程',
        dataIndex: 'CurrentNodeName',
        key: 'CurrentNodeName',
        width: 80,
      },
      {
        title: '报修时间',
        dataIndex: 'ApplyTime',
        key: 'ApplyTime',

        render: text => <span>{text ? moment(text).format('YYYY-MM-DD') : null}</span>,
      },
      {
        title: '维修单位',
        dataIndex: 'ApplyGroup',
        key: 'ApplyGroup',

      },
      {
        title: '是否完成',
        dataIndex: 'CurrentNode',
        key: 'CurrentNode',

        render: (text, record) => {
          if (text == 6) return '已完成';
          else return '未完成';

        }
      },
      {
        title: '完成时间',
        dataIndex: 'CheckTime',
        key: 'CheckTime',

        render: text => <span>{text ? moment(text).format('YYYY-MM-DD') : null}</span>,
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 180,
        render: (text, record) => {
         
          if (record.CurrentNode == 6) {
            return (
              <span>
                <a href="javascrips:;" onClick={() => {
                  router.push({ pathname: '/municipal/repair/desc', state: { record: record } });
                }}>

                  <Icon type="book" />
                  查看
                </a>
                <Divider type="vertical" />
                <Authorized authority={this.props.elementAuth['delete']}>
                <Popconfirm title="确定删除?" onConfirm={this.handleDelete.bind(this, record)}>
                  <a href="javascript:;">
                    <Icon type="delete" />
                    删除
                  </a>
                </Popconfirm>
                </Authorized>
              </span>
            );
          } else {
            
            return (
              <span>
                <a href="javascrips:;" onClick={() => {
                  router.push({ pathname: '/municipal/repair/desc', state: { record: record } });
                }}>
                  <Icon type="book" />
                  查看
                </a>
                <Divider type="vertical" />
                <Authorized authority={this.props.elementAuth['edit']}>
                <a href="javascrips:;" onClick={this.handleEdit.bind(this, record)}>
                  <Icon type="edit" />
                  编辑
                </a>
                </Authorized>
                <Divider type="vertical" />
                <Authorized authority={this.props.elementAuth['delete']}>
                <Popconfirm title="确定删除?" onConfirm={this.handleDelete.bind(this, record)}>
                  <a href="javascript:;">
                    <Icon type="delete" />
                    删除
                  </a>
                </Popconfirm>
                </Authorized>
              </span>
            );
          }
        },
      },
    ];
  };
  queryList = () => {
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.queryNode == 7) values.queryNode = null;
        this.GetList({
          queryName: values.queryName,
          queryNode: values.queryNode,
          StartTime: values.StartTime ? values.StartTime.format('YYYY-MM-DD') : null,
          EndTime: values.EndTime ? values.EndTime.format('YYYY-MM-DD') : null,
        });
      }
    });
  };
  resetData = () => {
    const { form } = this.props;
    form.resetFields();
    this.GetList();
  };

  GetList = ({ queryName = null, queryNode = null, StartTime = null, EndTime = null } = {}) => {
    this.dispatch({
      type: 'repair/fetchEquipmentList',
      payload: {
        queryName: queryName,
        queryNode: queryNode,
        StartTime: StartTime,
        EndTime: EndTime,
      },
      callback: response => {
        if (response.ErrorMessage) {
          message.error.error('获取设施维修清单失败');
          console.log(response.ErrorMessage);
        }
      },
    });
  };
  GetMaintainNode = () => {
    this.dispatch({
      type: 'repair/fetchMaintainNode',
      payload: {},
      callback: response => {
        if (response.ErrorMessage) {
          message.error('获取维修流程失败');
          console.log(response.ErrorMessage);
        }
      },
    });
  };
  handleEdit = record => {
    this.setState({ editObj: record }, () => {
      this.EditForm.setState({ visible: true });
    });
  };
  handleDelete = record => {
    const hide = message.loading('正在删除...', 0);
    this.dispatch({
      type: 'repair/fetchDeleteEquipment',
      payload: { ID: record.ID },
      callback: response => {
        hide();
        if (response.status) {
          message.success('删除成功');
        } else {
          message.error('删除失败');
          console.log(response.ErrorMessage);
        }
        this.queryList();
      },
    });
  };
  OnRef = (ref, payload) => {
    this[payload.type] = ref;
  };
  onChange = (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  };
  // getCheckboxProps= record => ({
  //   disabled: record.name === 'Disabled User', // Column configuration not to be checked
  //   name: record.name,
  // })

  componentDidMount = () => {
    this.GetMaintainNode();
    this.getAuth();

    if (!this.props.wxglList.length) this.GetList();
  };
  getAuth = () => {
    const { dispatch, currentUrl,match } = this.props;
    dispatch({ 
      type: 'global/fetchUrl', payload: match.url,callback: response => {
      } });
    dispatch({
      type: 'global/fetchAuthorityElements',
      payload: { url: match.url },
    });
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    const { wxglList, MaintainNodeList, loading,elementAuth } = this.props;
    console.log(elementAuth)
    const rowSelection = {
      onChange: this.onChange,
    };
    return (
      <Fragment>
        <Card style={{ margin: '10px' }}>
          <Form layout="inline">
            <FormItem label="设施名称">
              {getFieldDecorator('queryName', { initialValue: null })(
                <Input placeholder="设施名称" style={{ width: '200px' }} />
              )}
            </FormItem>
            <FormItem label="目前流程">
              {getFieldDecorator('queryNode', { initialValue: null })(
                <Select style={{ width: 120 }}>
                  {MaintainNodeList.length > 0
                    ? MaintainNodeList.map(item => {
                      return (
                        <Option key={item.Sort} value={item.Sort}>
                          {item.Title}
                        </Option>
                      );
                    })
                    : null}
                </Select>
              )}
            </FormItem>
            <FormItem label="起始时间">
              {getFieldDecorator('StartTime', { initialValue: null })(
                <DatePicker
                  placeholder="起始时间"
                  style={{ width: '200px' }}
                  format={'YYYY-MM-DD'}
                />
              )}
            </FormItem>
            <FormItem label="截止时间">
              {getFieldDecorator('EndTime', { initialValue: null })(
                <DatePicker
                  placeholder="截止时间"
                  style={{ width: '200px' }}
                  format={'YYYY-MM-DD'}
                />
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={this.queryList.bind(this)}>
                查询
              </Button>
            </FormItem>
            <FormItem>
              <Button onClick={this.resetData.bind(this, '')}>重置</Button>
            </FormItem>
            <Authorized authority={elementAuth['add']}>
            <FormItem>
              <Button
                type="primary"
                onClick={() => {
                  this.AddForm.setState({ visible: true });
                }}
              >
                新增
                </Button>
            </FormItem>
            </Authorized>
          </Form>
        </Card>
        <Card
          title={
            <span style={{ borderLeft: '4px solid #3CB371', paddingLeft: '10px' }}>
              设施维修清单
            </span>
          }
          style={{ margin: '10px' }}
        >
          <Table
            className={styles.RepairTable}
            size="small"
            align={'center'}
            loading={loading}
            bordered
            dataSource={wxglList}
            columns={this.returnColumn()}
            rowSelection={rowSelection}
          />
        </Card>

        <RepairAddForm OnRef={this.OnRef} queryList={this.queryList} />
        <RepairEditForm2
          OnRef={this.OnRef}
          queryList={this.queryList}
          editObj={this.state.editObj}
        />
      </Fragment>
    );
  }
}

export default Repair;
